package cn.fcq.org.service.impl;

import cn.fcq.basic.service.impl.BaseServiceImpl;
import cn.fcq.org.domain.Department;
import cn.fcq.org.mapper.DepartmentMapper;
import cn.fcq.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department>implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Transactional
    @Override
    public void save(Department department) {
        departmentMapper.save(department);
        this.update(department);


    }
    @Transactional
    @Override
    public void update(Department department) {
        String dirPath = "";
        if(department.getParent() == null){
            //1.新增的是顶级部门
            dirPath = "/"+department.getId();
        }else{
            //2.新增的是非顶级部门    找上级部门的dirpath + /自己id
            Department parent = departmentMapper.loadById(department.getParent().getId());
            dirPath = parent.getDirPath() + "/"+department.getId();
        }
        department.setDirPath(dirPath);
        departmentMapper.update(department);
    }
    /**
     * 无限极树
     *
     *    1.一次性查询出所有数据，放到内存 all
     *    2.从所有数据中找出第一层级 firstCourseType   我们需要返回的数据
     *    3.只要不是第一层级的，找自己的上级，并将自己放入上级的children中
     * @return
     */
    @Override
    public List<Department> queryTree(){
        //查询出所有数据
        List<Department> departments = departmentMapper.loadAll();
        // 把所有的数据转换成Map结构--后面查找自己的上级使用
        Map<Long, Department> allDepts = new HashMap<>();
        for (Department department:departments){
            allDepts.put(department.getId(),department);
        }
        //获取顶级部门
        List<Department> firstDepts = new ArrayList<>();
        for (Department tmp:departments){
            if (tmp.getParent_id()==null){
                //2.从所有数据中找出第一层级 firstCourseType   我们需要返回的数据
                firstDepts.add(tmp);
            }else {
                //3.只要不是第一层级的，找自己的上级，并将自己放入上级的children中
                Department parent = allDepts.get(tmp.getParent_id());
                if (parent != null){
                    parent.getChildren().add(tmp);
                }
            }
        }
        return firstDepts;
    }
}
